package com.xu.controller;

import com.xu.pojo.Student;
import com.xu.service.StudentService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/reg")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String age = req.getParameter("age");

//        ClassPathXmlApplicationContext ca = new ClassPathXmlApplicationContext("applicationContext.xml");

        WebApplicationContext ca=null;
        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
        //获取ServletContext中的容器对象，创建好的，拿来就用
        Object attribute = getServletContext().getAttribute(key);
        if(attribute != null){
             ca = (WebApplicationContext) attribute;
        }

/*        工具类 WebApplicationContextUtils 有一个方法专门用于从 ServletContext 中获取 Spring
        容器对象：getRequiredWebApplicationContext(ServletContext sc)*/
//        WebApplicationContext ca = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

        System.out.println("容器对象的信息"+ca);
        StudentService service = (StudentService) ca.getBean("studentService");
        Student student = new Student();
        student.setName(name);
        student.setEmail(email);
        student.setAge(Integer.valueOf(age));
        int i = service.insertStudent(student);
        if(i > 0){
            System.out.println("注册成功！");
        }
        req.getRequestDispatcher("/result.jsp").forward(req,resp);
    }
}
